﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;

using EMANIFEST.Common;
using EMANIFEST.Common.Validation;
using EMANIFEST.Dtos;
using EMANIFEST.ImportExcelData;
using EMANIFEST.eManifestService;
using EMANIFEST.ImportExcelData;

namespace EMANIFEST.CONTROLTEMPLATES.Emanifest_UI
{
    public partial class general : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                EmanifestServiceClient client = null;
                GeneralDeclarationDto general = null;
                List<PortDto> lstPort = null;
                string id = Request.QueryString["id"];
                #region Loading data
                try
                {
                    client = new EmanifestServiceClient();
                    //Loading Port                    
                    lstPort = Cache[CacheKey.CacheNameOfListPortInVN] as List<PortDto>;

                    if (lstPort == null)
                        lstPort = client.GetListPortInVN();

                    if (!string.IsNullOrEmpty(id))
                    {
                        general = client.GetGeneralDeclarationById(new Guid(id));
                        hdn.Value = id;
                    }
                }
                catch
                {
                    lblMessage.Text = "Communication error";
                }
                finally
                {
                    client.Close();
                }
                #endregion

                #region Binding
                if (general.DocumentId == new Guid(id))
                {
                    txtPosition.Text = general.PositionInPort;
                    ddlLastPort.SelectedValue = general.LastArrivalPortId.ToString();
                    txtPreviousPorts.Text = general.PreviousPorts;
                    txtSubsequentPorts.Text = general.SubsequentPorts;
                    txtParticularsOfVoyage.Text = general.ParticularsOfVoyage;
                    txtContactDetails.Text = general.ContactDetails;
                    txtDesProduct.Text = general.DescriptionOfCargo;
                    txtNumberCrews.Text = general.NumberOfCrews.ToString();
                    txtNumberCustomer.Text = general.NumberOfPassengers.ToString();
                    txtNode.Text = general.Remarks;
                    txtRequire.Text = general.Requirements;
                    txtNode.Text = general.Remarks;
                }
                ddlLastPort.DataSource = lstPort;
                ddlLastPort.DataTextField = "Name";
                ddlLastPort.DataValueField = "PortId";
                ddlLastPort.DataBind();
                #endregion

                #region insert to cache
                if (Cache[CacheKey.CacheNameOfListPortInVN] == null)
                    Cache.Insert(CacheKey.CacheNameOfListPortInVN, lstPort, null, DateTime.Now.AddHours(24), TimeSpan.Zero);
                //Cache.Insert(CacheKey.CacheNameOfDocumentStatus, lstStatus, null, DateTime.Now.AddHours(12), TimeSpan.Zero);
                #endregion
            }
        }

        protected void btn_Click(object sender, EventArgs e)
        {
            GeneralDeclarationDto general = new GeneralDeclarationDto();
            string rid = Request.QueryString["rid"];

            general.DocumentId = new Guid(rid);

            general.ContactDetails = txtNode.Text;
            general.CreaterId = EmanifestUser.FBAUserId;
            general.DateOfArrival = DateTime.Now;
            general.DeparturePortId = new Guid(ddlLastPort.SelectedValue);
            general.DescriptionOfCargo = txtDesProduct.Text;
            general.ItemStatus = 1;
            general.LastArrivalPortId = new Guid(ddlLastPort.SelectedValue);
            general.ModifiedDate = DateTime.Now;

            general.NumberOfCrews = string.IsNullOrEmpty(txtNumberCrews.Text)
                                        ? 0
                                        : Convert.ToDecimal(txtNumberCrews.Text);
            general.NumberOfPassengers = string.IsNullOrEmpty(txtNumberCustomer.Text)
                                        ? 0
                                        : Convert.ToDecimal(txtNumberCustomer.Text);
            general.PositionInPort = txtPosition.Text;
            general.PreviousPorts = txtPreviousPorts.Text;
            general.ParticularsOfVoyage = txtParticularsOfVoyage.Text;
            general.Remarks = txtNode.Text;
            general.Requirements = txtRequire.Text;
            general.SubsequentPorts = txtSubsequentPorts.Text;
            general.Remarks = txtNode.Text;
            general.Requirements = txtRequire.Text;

            //general.NumberOfPassengers = int.Parse(txtNumberCustomer.ToString());


            string id = hdn.Value;
            if (!string.IsNullOrEmpty(id))
            {
                general.GeneralDeclarationId = new Guid(id);
            }
            else
                general.GeneralDeclarationId = System.Guid.NewGuid();

            EmanifestServiceClient client = new EmanifestServiceClient();
            try
            {
                ResponseDto response = client.SaveGeneralDeclaration(general);
                client.Close();
                if (!response.IsSuccess)
                    lblMessage.Text = response.ErroeMessage;
                else
                {
                    Response.Redirect(string.Format("{0}?id={1}", RedirectToPage.record_add, rid));
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.ToString();
            }

        }

        //protected void btnUpload_Click(object sender, EventArgs e)
        //{
        //    if (fileUpload.HasFile)
        //    {
        //        string ext = fileUpload.FileName.Substring(fileUpload.FileName.LastIndexOf('.') + 1);

        //        //Validate
        //        if (!ValidationHelper.AllowExtensionUpload(ext)){
        //            lblMessage.Text = "File không hợp lệ. Hệ thống chỉ hỗ trợ upload file xls,xlsx,edi!";
        //            return;
        //        }

        //        if (ext.ToLower().Trim() == "edi")
        //        {

        //            UploadToSharepoint upload = new UploadToSharepoint();
        //            string site = Constant.siteUrl;
        //            Guid guid = System.Guid.NewGuid();
        //            string pathFileName = string.Empty;

        //            bool IsCompleted = upload.UploadFile(fileUpload, site, guid.ToString() + ".txt", out pathFileName);

        //            if (IsCompleted)
        //            {
        //                string rid = Request.QueryString["rid"];
        //                var ediUploadFileDto = new EdiUploadFileDto();

        //                //ediUploadFileDto.CreatedDate
        //                //ediUploadFileDto.CreaterId = CurrentUser.ID;
        //                ediUploadFileDto.DocumentId = new Guid(rid);
        //                ediUploadFileDto.EdiId = guid;
        //                ediUploadFileDto.Status = 1;
        //                ediUploadFileDto.UploadFileName = pathFileName;
        //                var client = new EmanifestServiceClient();

        //                ResponseDto response = client.SaveEdiFile(ediUploadFileDto);

        //                client.Close();

        //                if (response.IsSuccess)
        //                {
        //                    lblMessage.Text = "Upload file thành công!";
        //                }
        //                else
        //                {
        //                    lblMessage.Text = response.ErroeMessage;
        //                }
        //            }
        //            else
        //            {
        //                lblMessage.Text = "Có lỗi trong quá trình upload file";
        //            }
        //        }
        //        else
        //        {
        //            var import = new ImportExcelDataClient();
        //            //string fileName = string.Empty;

        //            string fileName = import.UploadFileData(fileUpload.FileContent);

        //            if (!string.IsNullOrEmpty(hdn.Value))
        //            {
        //                Guid guid = new Guid(hdn.Value);
        //                //ResponseDto response = new ResponseDto();

        //                ResponseDto response = import.ImportGeneralDeclarationData(guid, fileName, new EmanifestCommon().IsNewDocument(guid) == false);



        //                if (response.IsSuccess)
        //                {
        //                    import.Close();
        //                    Response.Redirect(string.Format("{0}?id={1}", RedirectToPage.record_add, hdn.Value));
        //                }
        //                else
        //                {
        //                    lblMessage.Text = response.ErroeMessage;
        //                }
        //            }
        //            import.Close();
        //        }
        //    }
        //}

    }
}
